package com.supplychainapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.BizCode;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.dao.prod.ScmTbcustMapper;
import com.supplychainapi.domain.IncrementRate;
import com.supplychainapi.domain.PriceLvl;
import com.supplychainapi.domain.SaleMode;
import com.supplychainapi.model.ScmTbcust;
import com.supplychainapi.model.ScmTbseqno;
import com.supplychainapi.model.ScmTbtreebuild;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.service.IScmTbcustService;
import com.supplychainapi.service.IScmTbtreebuildService;
import com.supplychainapi.service.TbSeqNoService;
import com.supplychainapi.utils.Constants;
import com.supplychainapi.utils.HelpCodeUtils;
import com.supplychainapi.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * Created by shenhong on 2017/10/14.
 */

@Service
public class ScmTbcustServiceImpl implements IScmTbcustService {

    private Logger logger = LoggerFactory.getLogger(ScmTbcustServiceImpl.class);

    @Autowired
    private ScmTbcustMapper scmTbcustMapper;

    @Autowired
    TbSeqNoService tbSeqNoService;
    @Autowired
    private IScmTbtreebuildService treebuildService;

    @Override
    public void addScmTbcustInfo(ScmTbcust cust) throws ServiceException {
        if (StringUtil.checkIsEmoji(cust.getFsCustName())) {
            throw ExceptionMessage.emoji_failed.getServiceException();
        }
        if(cust.getFsCustId()==null || cust.getFsCustId().trim().equals("")){
            logger.info("----开始自动生成编号-----");
            ScmTbseqno model = new ScmTbseqno();
            model.setFsShopGUID(cust.getFsShopGUID());
            model.setFsCls(Constants.CUST_CLASS);
            String fsCustId = tbSeqNoService.selectSeqNo(model);
            cust.setFsCustId(fsCustId);
        }else{
            logger.info("手动填写编号业务处理");
            ScmTbseqno tbseqno1=new ScmTbseqno();
            tbseqno1.setFiSeqNo(cust.getFsCustId());
            tbseqno1.setFsCls(Constants.CUST_CLASS);
            tbseqno1.setFsShopGUID(cust.getFsShopGUID());
            tbSeqNoService.checkCode(tbseqno1);
            tbSeqNoService.insert(tbseqno1,cust.getFsShopGUID());
        }
        //根据挂载的节点ID，找到父级的的信息
        String fsNodeCode = cust.getFsNodeCode();
        List<ScmTbtreebuild> treeList = treebuildService.getParentNodeCodeAndNodeCodeInfo(cust.getFsShopGUID(), Constants.CUST_CLASS, fsNodeCode);
        String fsNodeFullText = "";
        if (treeList != null && treeList.size() > 0) {
            for (ScmTbtreebuild scmTbtreebuild : treeList) {
                fsNodeFullText = fsNodeFullText.concat(scmTbtreebuild.getFsNodeText() + "_");
            }
        }
        cust.setFsNodeFullText(fsNodeFullText.concat(cust.getFsCustName()));
        cust.setFsHelpCode(HelpCodeUtils.String2Alpha(cust.getFsCustName()));
        cust.setFsCreateTime(new Date());
        cust.setFsUpdateTime(new Date());
        cust.setFsHelpCode(HelpCodeUtils.String2Alpha(cust.getFsCustName()));
        scmTbcustMapper.insertSelective(cust);
    }

    @Override
    public void updateScmTbcustInfo(ScmTbcust cust) throws ServiceException {
        cust.setFsHelpCode(HelpCodeUtils.String2Alpha(cust.getFsCustName()));
        scmTbcustMapper.updateByPrimaryKeySelective(cust);
    }
    @Override
    public ScmTbcust getCustInfo(String fsCustId) {
        logger.info("fsCust={}",fsCustId);
        ScmTbcust scmTbcust = scmTbcustMapper.getCustInfo(fsCustId);
        return scmTbcust;
    }
    @Override
    public ScmTbcust getCustByFsShopGUIDList(String fsShopGUID, String fsCustId)
            throws ServiceException {
        ScmTbcust scmTbcust = scmTbcustMapper.getCustByFsShopGUIDList(fsShopGUID,fsCustId);
        return scmTbcust;
    }

    @Override
    public void deleteCustInfo(List<String> fsCustIdList, List<String> fsShopGUIDList) throws ServiceException {
        if(fsCustIdList==null || fsCustIdList.size()<=0){
            throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
        }

        if(fsShopGUIDList==null || fsShopGUIDList.size()<=0){
            throw new ServiceException(BizCode.FAIL.getNum(), BizCode.PARAM_NULL.getDesc());
        }

        Map<String, Object> parameterMap = new HashMap<String, Object>();
        parameterMap.put("fsSupplierIdList", fsCustIdList);
        parameterMap.put("fsShopGUIDList", fsShopGUIDList);
        scmTbcustMapper.deleteCustInfo(parameterMap);
    }

    @Override
    public List<ScmTbcust> getByKeyWordCustInfoList(String keyWord, Integer page, Integer pageSize)
            throws ServiceException {
        List<ScmTbcust> scmTbcustList = scmTbcustMapper.getByKeyWordCustInfoList(keyWord, page, pageSize);
        return scmTbcustList;
    }

    @Override
    public List<ScmTbcust> getCustListInfo(String fsShopGUID, String fsNodeCode, Integer page, Integer pageSize)
            throws ServiceException {
        logger.info("fsShopGUID={},fsNodeCode={},page={},pageSize={}",fsShopGUID,fsNodeCode,page,pageSize);
        if(page!=null){
            page = (page-1) * pageSize;
        }else{
            page = 0;
        }
        List<ScmTbcust> custListInfo = scmTbcustMapper.getCustListInfo(fsShopGUID,fsNodeCode,page,pageSize);
        return custListInfo;
    }

    @Override
    public List<ScmTbcust> getCustByFsCustNameListInfo(String fsShopGUID, String fsCustName,
                                                            Integer page, Integer pageSize) throws ServiceException {
        logger.info("fsShopGUID={},fsCustName={},page={},pageSize={}",fsShopGUID,fsCustName,page,pageSize);
        if(page!=null){
            page = (page-1) * pageSize;
        }else{
            page = 0;
        }
        List<ScmTbcust> custByNameListInfo = scmTbcustMapper.getCustByFsCustNameListInfo(fsShopGUID,fsCustName,page,pageSize);
        return custByNameListInfo;
    }

    @Override
    public Boolean getCustNameIsExit(String fsShopGUID, String fsCustName, String fsCustId, String type) throws ServiceException {
        logger.info("判断客户名称是否重复 fsShopGUID={},fsStorageName={},fsStorageId={},type={}", fsShopGUID, fsCustName, fsCustId, type);
        Integer countNumber = scmTbcustMapper.getCustNameIsExit(fsShopGUID, fsCustName);
        if (type.equals("update")) {
            //当前传入的客户名称和数据库查询出来的名称相同不做处理
            ScmTbcust cust = scmTbcustMapper.getCustByFsShopGUIDList(fsShopGUID, fsCustId);
            if (cust != null && cust.getFsCustName().equals(fsCustName)) {
                return false;
            }
        }
        logger.info("根据当前门店和客户名查询返回结果集=" + countNumber);
        return countNumber != null && countNumber > 0;
    }


    @Override
    public int count(ScmTbcust param) {
        return scmTbcustMapper.selectCount(param);
    }


    @Override
    public List<ColTitle> getSchema() {
        List<ColTitle> list = new ArrayList<ColTitle>();
        list.add(new ColTitle("fsCustId", "客户代码", "center", 100));
        list.add(new ColTitle("fsCustName", "客户名称", "center", 100));
        list.add(new ColTitle("fsContact", "联系人", "center", 100));
        list.add(new ColTitle("fsCellphoneCt", "联系手机", "center", 100));
        list.add(new ColTitle("fiStatus", "状态", "center", 100));
        list.add(new ColTitle("__EDIT__", "操作", null, 150, "fsCustId"));
        return list;
    }


    @Override
    public PageInfo getCustListInfoPC(String fsShopGUID, String keyWord, String fsNodeCode, Integer pageNum,
                                      Integer pageSize) throws ServiceException {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("fsCreateTime DESC");
        List<ScmTbcust> custList = scmTbcustMapper.getCustListInfoPC(fsShopGUID, keyWord, fsNodeCode);
        return new PageInfo(custList);
    }

    @Override
    public PageInfo getChoiceCustListInfo(String fsShopGUID, String keyWord, String fsNodeCode,
                                          Integer pageNum, Integer pageSize) throws ServiceException {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("fsCreateTime DESC");
        List<ScmTbcust> custList = scmTbcustMapper.getChoiceCustListInfo(fsShopGUID, keyWord, fsNodeCode);
        return new PageInfo(custList);
    }

    /*@Override
    public ScmTbsupplier getSupplierDetails(String fsShopGUID, String fsCustId) throws ServiceException {
        ScmTbcust cust = scmTbcustMapper.getSupplierPhoneDetailsInfo(fsShopGUID, fsCustId);
        return cust;
    }*/

    @Override
    public Map<String, List<IncrementRate>> getIncrementRate() {
        Map<String, List<IncrementRate>> map = Maps.newHashMap();
        List<IncrementRate> listIncrementRate = Lists.newArrayList();
        listIncrementRate.add(new IncrementRate("0", "0"));
        listIncrementRate.add(new IncrementRate("3", "3"));
        listIncrementRate.add(new IncrementRate("6", "6"));
        listIncrementRate.add(new IncrementRate("11", "11"));
        listIncrementRate.add(new IncrementRate("13", "13"));
        listIncrementRate.add(new IncrementRate("17", "17"));
        map.put("listIncrementRate", listIncrementRate);
        return map;
    }

    @Override
    public Map<String, List<SaleMode>> getSaleMode() {
        Map<String, List<SaleMode>> map = Maps.newHashMap();
        List<SaleMode> listSaleMode = Lists.newArrayList();
        listSaleMode.add(new SaleMode("1", "赊销"));
        listSaleMode.add(new SaleMode("2", "现销"));
        map.put("listSaleMode", listSaleMode);
        return map;
    }

    @Override
    public Map<String, List<PriceLvl>> getPriceLvl() {
        Map<String, List<PriceLvl>> map = Maps.newHashMap();
        List<PriceLvl> listPriceLvl = Lists.newArrayList();
        listPriceLvl.add(new PriceLvl("1", "A"));
        listPriceLvl.add(new PriceLvl("2", "B"));
        listPriceLvl.add(new PriceLvl("3", "c"));
        map.put("listPriceLvl", listPriceLvl);
        return map;
    }

    @Override
    public int updateFullText(ScmTbcust tbcust) {
        Example example = new Example(ScmTbcust.class);
        example.createCriteria().andEqualTo("fsCustId", tbcust.getFsCustId()).andEqualTo("fsShopGUID", tbcust.getFsShopGUID());
        tbcust.setFsNodeFullText(tbcust.getFsNodeFullText().concat("_").concat(tbcust.getFsCustName()));
        return scmTbcustMapper.updateByExampleSelective(tbcust, example);

    }

    @Override
    public List<ScmTbcust> findFullCode(String fsShopGuid, String fullCode) throws ServiceException {
        Example example = new Example(ScmTbcust.class);
        example.createCriteria().andEqualTo("fsShopGUID", fsShopGuid).andLike("fsNodeFullCode", "%".concat(fullCode).concat("%"));
        return scmTbcustMapper.selectByExample(example);
    }
}
